package ch.mdd.siegfried
import grails.converters.JSON
import java.io.FileInputStream;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;


class DataCartController {

    def index() { }
    
    def forcedl(){
        log.info("forcedl =>" +params);
        
            
        if(params.filearray == null|| params.filearray ==""){log.info("parameters incomplete");return;};
        
        String sCurrentLine ="";
        String path = grailsAttributes.getApplicationContext().getResource("/").getFile().toString();
        String fileName = path +"/Siegfried/en/download.html";
        
        LinkedList<String> fileList =new LinkedList<String>();
       
             
        if(params.filearray.contains(",")){
            params.filearray.split(",").each() { it ->
                it = it.replace("..",path+"/Siegfried/");
                fileList.add(it);
            }
        }
        else{
            String temp = params.filearray.replace("..",path+"/Siegfried/");
            fileList.add( temp);
        }
        println fileList;
        println "break";
        String fileNameOut = "outfile.zip";
        Zip.run(fileList);
        File file = new File(fileNameOut);

        if (file.exists()) {
            
            response.setContentType("application/zip")
            response.setHeader("Content-disposition", "filename=${fileNameOut}")
            response.setHeader("Content-Disposition", "attachment; filename=\"" + "SiegfriedFiles.zip" + "\"");
            response.outputStream << file.bytes;
            return;
        }
            /**   println fileList;
            println "end of print";
            response.setContentType("application/octet-stream")
            response.setHeader("Content-disposition", "filename=${"fileName"}")
            response.outputStream << "result";
            return
             **/

        
        
        }
    
        def asyncGetFiles(){
            log.info(params);

            if(params.result ==null || params.result =="" ){
                return;
            }
            String[] hrefs;
            if(params.result.contains(',')){
                hrefs = params.result.split(',');
            
            }else{
                hrefs = [params.result];
            }
            println File.separator
        
            def linkItems=[];
        
        
            for (String href : hrefs) {
                def linkMap =[:];
                linkMap.href = href;
                linkMap.text = href.substring(href.lastIndexOf('/')+1,href.length());
                linkItems.add(linkMap);
       
            }
        
            //render linkItems as JSON
            //redirect(controller: "dataCart", action: "forcedl")
            //return;
            /**

            if(params.result == null|| params.result ==""){log.info("parameters incomplete");return;};
            String sCurrentLine ="";
            String path = grailsAttributes.getApplicationContext().getResource("/").getFile().toString();
            String fileName = path +"/Siegfried/en/download.html";
        
            LinkedList<String> fileList =new LinkedList<String>();
        
            if(params.result.contains(",")){
            params.result.split(",").each() { it ->
            it = it.replace("..",path+"/Siegfried/");
            fileList.add(it);
            } 
            
            }else{
            String temp = params.result.replace("..",path+"/Siegfried/");
            fileList.add( temp);
            }
            println fileList;
            println "break";
            String fileNameOut = "outfile.zip";
            Zip.run(fileList);
            File file = new File(fileNameOut);

            if (file.exists()) {
            
            response.setContentType("application/zip")
            response.setHeader("Content-disposition", "filename=${fileNameOut}")
            response.setHeader("Content-Disposition", "attachment; filename=\"" + "pictureName" + "\"");
            response.outputStream << file.bytes;
            return;
            }

        
        
        

            /**
            BufferedReader br = new BufferedReader(new FileReader(fileName));
            String html="";
            while ((sCurrentLine = br.readLine()) != null) {
            html += sCurrentLine ;
            }
            Document doc = Jsoup.parse(html);
            Element content = doc.getElementById("download-table");
        
        
        
            def linkItems=[];
        
            Elements links = content.getElementsByTag("a");
            for (Element link : links) {
            def linkMap =[:];
            linkMap.href = link.attr("href");
            linkMap.text = link.text();
            linkItems.add(linkMap);
       
            }
        
            render linkItems as JSON
            /**
        
        
            if (params.table) text = doc.select("div.contentPart > table").text();
            println text.length();
            //String title = doc.select("div.contentPart > h2").text();
            String title = doc.select("title").text();
                
        
            int ch;
            StringBuffer strContent = new StringBuffer("");
            FileInputStream fin = null;


            File fl = new File("C:/Users/d.guevara/Dropbox/Spaces/NetBeans/MDDFactChecker/MDDFactChecker/resources/SWISSLIFE2011/download/SL_group_auditor_ye_2011_en.pdf:\5SummaryInformation");
            println fl.getName();
         
            fin =  new FileInputStream(fl);

            while ((ch = fin.read()) != -1)
            strContent.append((char) ch);

            fin.close();

            println "File contents :";
            //  println strContent;

            def files =[];
            new File("C:/Users/d.guevara/Dropbox/Spaces/NetBeans/MDDFactChecker/MDDFactChecker/resources/SWISSLIFE2011/download").eachFile(){ file->  
                      
            files << file.getName();
            int x =file.length()/1024;
           
            //  println x;
            }  
            def items = [files:files]
            render items as JSON
             **/
        }
    }
